<template>
  <div class="ai-configuration">
    <!-- AI配置标题 -->
    <div class="section-header">
      <h2 class="section-title">AI配置管理</h2>
      <p class="section-description">配置AI模型、训练参数和智能算法设置</p>
    </div>

    <!-- 模型管理 -->
    <div class="aps-section">
      <el-row>
        <span
          style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          "
        >
          AI模型管理
        </span>
        <el-button type="text" style="float: right" @click="toggleModelConfig">
          {{ showModelConfig ? "收起" : "展开" }}
        </el-button>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showModelConfig" style="margin-top: 20px">
          <el-row :gutter="20">
            <!-- 模型选择 -->
            <el-col :span="12">
              <el-form label-position="top" label-width="120px">
                <el-form-item label="当前模型">
                  <el-select
                    v-model="modelConfig.currentModel"
                    placeholder="选择AI模型"
                  >
                    <el-option
                      v-for="model in availableModels"
                      :key="model.id"
                      :label="model.name"
                      :value="model.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="模型版本">
                  <el-input
                    v-model="modelConfig.version"
                    placeholder="如: v2.1.0"
                  />
                </el-form-item>
                <el-form-item label="模型描述">
                  <el-input
                    v-model="modelConfig.description"
                    type="textarea"
                    :rows="3"
                    placeholder="模型功能描述..."
                  />
                </el-form-item>
              </el-form>
            </el-col>

            <!-- 模型状态 -->
            <el-col :span="12">
              <div class="model-status-card">
                <h4>模型状态</h4>
                <el-descriptions :column="1" border>
                  <el-descriptions-item label="状态">
                    <el-tag :type="getModelStatusType(modelConfig.status)">
                      {{ modelConfig.status }}
                    </el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="准确率">
                    <el-progress
                      :percentage="modelConfig.accuracy"
                      :color="progressColors"
                      :stroke-width="6"
                    />
                  </el-descriptions-item>
                  <el-descriptions-item label="最后训练时间">
                    {{ modelConfig.lastTrainingTime }}
                  </el-descriptions-item>
                  <el-descriptions-item label="训练样本数">
                    {{ modelConfig.trainingDataSize.toLocaleString() }}
                  </el-descriptions-item>
                </el-descriptions>

                <div style="margin-top: 20px; text-align: center">
                  <el-button
                    type="primary"
                    class="idoo-details-add"
                    @click="handleTrainModel"
                  >
                    <el-icon><VideoPlay /></el-icon>
                    开始训练
                  </el-button>
                  <el-button @click="handleTestModel">
                    <el-icon><Aim /></el-icon>
                    测试模型
                  </el-button>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </transition>
    </div>

    <!-- 训练参数 -->
    <div class="aps-section">
      <el-row>
        <span
          style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          "
        >
          训练参数配置
        </span>
        <el-button
          type="text"
          style="float: right"
          @click="toggleTrainingParams"
        >
          {{ showTrainingParams ? "收起" : "展开" }}
        </el-button>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showTrainingParams" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form label-position="right" label-width="120px">
                <el-form-item label="学习率">
                  <el-input-number
                    v-model="trainingParams.learningRate"
                    :min="0.0001"
                    :max="1"
                    :step="0.0001"
                    :precision="4"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="批处理大小">
                  <el-input-number
                    v-model="trainingParams.batchSize"
                    :min="1"
                    :max="512"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="训练轮数">
                  <el-input-number
                    v-model="trainingParams.epochs"
                    :min="1"
                    :max="1000"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="验证集比例">
                  <el-slider
                    v-model="trainingParams.validationSplit"
                    :min="0.1"
                    :max="0.5"
                    :step="0.05"
                    show-input
                    :format-tooltip="formatTooltip"
                  />
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12">
              <el-form label-position="right" label-width="120px">
                <el-form-item label="优化器">
                  <el-select
                    v-model="trainingParams.optimizer"
                    style="width: 100%"
                  >
                    <el-option label="Adam" value="adam" />
                    <el-option label="SGD" value="sgd" />
                    <el-option label="RMSprop" value="rmsprop" />
                    <el-option label="AdaGrad" value="adagrad" />
                  </el-select>
                </el-form-item>
                <el-form-item label="损失函数">
                  <el-select
                    v-model="trainingParams.lossFunction"
                    style="width: 100%"
                  >
                    <el-option label="均方误差" value="mse" />
                    <el-option label="交叉熵" value="crossentropy" />
                    <el-option label="Huber损失" value="huber" />
                  </el-select>
                </el-form-item>
                <el-form-item label="早停耐心值">
                  <el-input-number
                    v-model="trainingParams.earlyStopping"
                    :min="5"
                    :max="100"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="使用GPU">
                  <el-switch v-model="trainingParams.useGPU" />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </transition>
    </div>

    <!-- 智能算法配置 -->
    <div class="aps-section">
      <el-row>
        <span
          style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          "
        >
          智能算法配置
        </span>
        <el-button
          type="text"
          style="float: right"
          @click="toggleAlgorithmConfig"
        >
          {{ showAlgorithmConfig ? "收起" : "展开" }}
        </el-button>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showAlgorithmConfig" style="margin-top: 20px">
          <el-tabs v-model="activeAlgorithmTab" type="border-card">
            <!-- 强化学习 -->
            <el-tab-pane label="强化学习" name="rl">
              <el-form label-position="right" label-width="140px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="算法类型">
                      <el-select
                        v-model="algorithmConfig.rl.algorithm"
                        style="width: 100%"
                      >
                        <el-option label="DQN" value="dqn" />
                        <el-option label="PPO" value="ppo" />
                        <el-option label="A3C" value="a3c" />
                        <el-option label="DDPG" value="ddpg" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="折扣因子">
                      <el-input-number
                        v-model="algorithmConfig.rl.discountFactor"
                        :min="0.1"
                        :max="1"
                        :step="0.01"
                        :precision="2"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="探索率">
                      <el-input-number
                        v-model="algorithmConfig.rl.explorationRate"
                        :min="0.01"
                        :max="1"
                        :step="0.01"
                        :precision="2"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="经验回放大小">
                      <el-input-number
                        v-model="algorithmConfig.rl.replayBufferSize"
                        :min="1000"
                        :max="100000"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="目标网络更新">
                      <el-input-number
                        v-model="algorithmConfig.rl.targetUpdateFreq"
                        :min="100"
                        :max="10000"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="奖励函数权重">
                      <el-slider
                        v-model="algorithmConfig.rl.rewardWeight"
                        :min="0.1"
                        :max="2"
                        :step="0.1"
                        show-input
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>

            <!-- 遗传算法 -->
            <el-tab-pane label="遗传算法" name="ga">
              <el-form label-position="right" label-width="140px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="种群大小">
                      <el-input-number
                        v-model="algorithmConfig.ga.populationSize"
                        :min="10"
                        :max="1000"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="交叉概率">
                      <el-input-number
                        v-model="algorithmConfig.ga.crossoverRate"
                        :min="0.1"
                        :max="1"
                        :step="0.01"
                        :precision="2"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="变异概率">
                      <el-input-number
                        v-model="algorithmConfig.ga.mutationRate"
                        :min="0.001"
                        :max="0.5"
                        :step="0.001"
                        :precision="3"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="最大代数">
                      <el-input-number
                        v-model="algorithmConfig.ga.maxGenerations"
                        :min="10"
                        :max="1000"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>

            <!-- 神经网络 -->
            <el-tab-pane label="神经网络" name="nn">
              <el-form label-position="right" label-width="140px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="隐藏层数">
                      <el-input-number
                        v-model="algorithmConfig.nn.hiddenLayers"
                        :min="1"
                        :max="10"
                        style="width: 100%"
                      />
                    </el-form-item>
                    <el-form-item label="每层神经元数">
                      <el-input-number
                        v-model="algorithmConfig.nn.neuronsPerLayer"
                        :min="10"
                        :max="1000"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="激活函数">
                      <el-select
                        v-model="algorithmConfig.nn.activation"
                        style="width: 100%"
                      >
                        <el-option label="ReLU" value="relu" />
                        <el-option label="Sigmoid" value="sigmoid" />
                        <el-option label="Tanh" value="tanh" />
                        <el-option label="Leaky ReLU" value="leaky_relu" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="Dropout率">
                      <el-input-number
                        v-model="algorithmConfig.nn.dropoutRate"
                        :min="0"
                        :max="0.8"
                        :step="0.1"
                        :precision="1"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </transition>
    </div>

    <!-- 数据管理 -->
    <div class="aps-section">
      <el-row>
        <span
          style="
            font-weight: 600;
            margin-top: 1px;
            font-size: large;
            color: rgb(1, 128, 165);
          "
        >
          训练数据管理
        </span>
        <el-button
          type="text"
          style="float: right"
          @click="toggleDataManagement"
        >
          {{ showDataManagement ? "收起" : "展开" }}
        </el-button>
      </el-row>
      <transition name="slide-toggle">
        <div v-show="showDataManagement" style="margin-top: 20px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="data-card">
                <template #header>
                  <span>训练数据集</span>
                </template>
                <el-statistic
                  title="样本数量"
                  :value="dataManagement.trainingDataCount"
                  suffix="条"
                />
                <div style="margin-top: 15px">
                  <el-button
                    type="primary"
                    size="small"
                    class="idoo-details-button"
                  >
                    <el-icon><Upload /></el-icon>
                    上传数据
                  </el-button>
                  <el-button size="small">
                    <el-icon><View /></el-icon>
                    查看数据
                  </el-button>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="data-card">
                <template #header>
                  <span>测试数据集</span>
                </template>
                <el-statistic
                  title="样本数量"
                  :value="dataManagement.testDataCount"
                  suffix="条"
                />
                <div style="margin-top: 15px">
                  <el-button
                    type="primary"
                    size="small"
                    class="idoo-details-button"
                  >
                    <el-icon><Upload /></el-icon>
                    上传数据
                  </el-button>
                  <el-button size="small">
                    <el-icon><View /></el-icon>
                    查看数据
                  </el-button>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="data-card">
                <template #header>
                  <span>数据质量</span>
                </template>
                <el-progress
                  type="circle"
                  :percentage="dataManagement.dataQuality"
                  :color="progressColors"
                />
                <div style="margin-top: 15px">
                  <el-button size="small">
                    <el-icon><Refresh /></el-icon>
                    质量检查
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { VideoPlay, Aim, Upload, View, Refresh } from "@element-plus/icons-vue";

export default {
  name: "AIConfiguration",
  components: {
    VideoPlay,
    Aim,
    Upload,
    View,
    Refresh,
  },
  setup() {
    // 显示控制
    const showModelConfig = ref(true);
    const showTrainingParams = ref(true);
    const showAlgorithmConfig = ref(true);
    const showDataManagement = ref(true);
    const activeAlgorithmTab = ref("rl");

    // 可用模型列表
    const availableModels = ref([
      { id: "aps_v1", name: "APS排程模型 v1.0" },
      { id: "aps_v2", name: "APS排程模型 v2.0" },
      { id: "optimization_v1", name: "优化算法模型 v1.0" },
      { id: "prediction_v1", name: "预测模型 v1.0" },
    ]);

    // 模型配置
    const modelConfig = reactive({
      currentModel: "aps_v2",
      version: "v2.1.0",
      description: "基于深度强化学习的智能排程模型，支持多目标优化和动态调度",
      status: "已部署",
      accuracy: 94,
      lastTrainingTime: "2024-01-15 14:30:00",
      trainingDataSize: 50000,
    });

    // 训练参数
    const trainingParams = reactive({
      learningRate: 0.001,
      batchSize: 32,
      epochs: 100,
      validationSplit: 0.2,
      optimizer: "adam",
      lossFunction: "mse",
      earlyStopping: 10,
      useGPU: true,
    });

    // 算法配置
    const algorithmConfig = reactive({
      rl: {
        algorithm: "ppo",
        discountFactor: 0.95,
        explorationRate: 0.1,
        replayBufferSize: 10000,
        targetUpdateFreq: 1000,
        rewardWeight: 1.0,
      },
      ga: {
        populationSize: 100,
        crossoverRate: 0.8,
        mutationRate: 0.01,
        maxGenerations: 200,
      },
      nn: {
        hiddenLayers: 3,
        neuronsPerLayer: 128,
        activation: "relu",
        dropoutRate: 0.2,
      },
    });

    // 数据管理
    const dataManagement = reactive({
      trainingDataCount: 45000,
      testDataCount: 15000,
      dataQuality: 92,
    });

    // 进度条颜色配置
    const progressColors = [
      { color: "#f56c6c", percentage: 20 },
      { color: "#e6a23c", percentage: 40 },
      { color: "#6f7ad3", percentage: 60 },
      { color: "#1989fa", percentage: 80 },
      { color: "#714B67", percentage: 100 },
    ];

    // 切换显示状态
    const toggleModelConfig = () => {
      showModelConfig.value = !showModelConfig.value;
    };

    const toggleTrainingParams = () => {
      showTrainingParams.value = !showTrainingParams.value;
    };

    const toggleAlgorithmConfig = () => {
      showAlgorithmConfig.value = !showAlgorithmConfig.value;
    };

    const toggleDataManagement = () => {
      showDataManagement.value = !showDataManagement.value;
    };

    // 工具函数
    const getModelStatusType = (status) => {
      const typeMap = {
        已部署: "success",
        训练中: "warning",
        未部署: "info",
        错误: "danger",
      };
      return typeMap[status] || "info";
    };

    const formatTooltip = (val) => {
      return `${(val * 100).toFixed(0)}%`;
    };

    // 操作方法
    const handleTrainModel = () => {
      ElMessage.success("开始训练模型...");
      modelConfig.status = "训练中";
    };

    const handleTestModel = () => {
      ElMessage.info("正在测试模型性能...");
    };

    // 配置管理方法
    const getConfigData = () => {
      return {
        modelConfig: { ...modelConfig },
        trainingParams: { ...trainingParams },
        algorithmConfig: JSON.parse(JSON.stringify(algorithmConfig)),
        dataManagement: { ...dataManagement },
      };
    };

    const loadConfigData = (data) => {
      if (data.modelConfig) {
        Object.assign(modelConfig, data.modelConfig);
      }
      if (data.trainingParams) {
        Object.assign(trainingParams, data.trainingParams);
      }
      if (data.algorithmConfig) {
        Object.assign(algorithmConfig, data.algorithmConfig);
      }
      if (data.dataManagement) {
        Object.assign(dataManagement, data.dataManagement);
      }
    };

    const validateConfig = () => {
      const errors = [];

      // 验证模型配置
      if (!modelConfig.currentModel) {
        errors.push("请选择当前使用的AI模型");
      }
      if (!modelConfig.version) {
        errors.push("请填写模型版本");
      }

      // 验证训练参数
      if (trainingParams.learningRate <= 0) {
        errors.push("学习率必须大于0");
      }
      if (trainingParams.batchSize <= 0) {
        errors.push("批处理大小必须大于0");
      }
      if (trainingParams.epochs <= 0) {
        errors.push("训练轮数必须大于0");
      }

      return {
        valid: errors.length === 0,
        errors,
      };
    };

    const resetConfig = () => {
      // 重置模型配置
      Object.assign(modelConfig, {
        currentModel: "aps_v2",
        version: "v2.1.0",
        description: "基于深度强化学习的智能排程模型",
        status: "已部署",
        accuracy: 94,
        lastTrainingTime: "2024-01-15 14:30:00",
        trainingDataSize: 50000,
      });

      // 重置训练参数
      Object.assign(trainingParams, {
        learningRate: 0.001,
        batchSize: 32,
        epochs: 100,
        validationSplit: 0.2,
        optimizer: "adam",
        lossFunction: "mse",
        earlyStopping: 10,
        useGPU: true,
      });

      // 重置算法配置
      Object.assign(algorithmConfig.rl, {
        algorithm: "ppo",
        discountFactor: 0.95,
        explorationRate: 0.1,
        replayBufferSize: 10000,
        targetUpdateFreq: 1000,
        rewardWeight: 1.0,
      });
    };

    return {
      // 显示控制
      showModelConfig,
      showTrainingParams,
      showAlgorithmConfig,
      showDataManagement,
      activeAlgorithmTab,

      // 数据
      availableModels,
      modelConfig,
      trainingParams,
      algorithmConfig,
      dataManagement,
      progressColors,

      // 切换方法
      toggleModelConfig,
      toggleTrainingParams,
      toggleAlgorithmConfig,
      toggleDataManagement,

      // 工具方法
      getModelStatusType,
      formatTooltip,

      // 操作方法
      handleTrainModel,
      handleTestModel,

      // 配置方法
      getConfigData,
      loadConfigData,
      validateConfig,
      resetConfig,
    };
  },
};
</script>

<style scoped>
.ai-configuration {
  padding: 0;
}

.section-header {
  margin-bottom: 30px;
  text-align: center;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #714b67;
  margin-bottom: 10px;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.section-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.aps-section {
  background-color: #ebebeb;
  padding: 15px;
  margin-top: 20px;
  border-radius: 5px;
}

.slide-toggle-enter-active,
.slide-toggle-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-toggle-enter,
.slide-toggle-leave-to {
  max-height: 0;
  opacity: 0;
}

.slide-toggle-enter {
  max-height: 0;
}

.slide-toggle-leave-to {
  max-height: 0;
}

.model-status-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.model-status-card h4 {
  color: #714b67;
  margin-bottom: 15px;
  text-align: center;
}

.data-card {
  height: 200px;
  text-align: center;
}

:deep(.el-form-item__label) {
  color: #714b67 !important;
  font-weight: 600;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-tabs__header) {
  background-color: #f8f9fa;
}

:deep(.el-tabs__item) {
  color: #714b67;
}

:deep(.el-tabs__item.is-active) {
  color: #922575;
}

:deep(.el-statistic__content) {
  text-align: center;
}

:deep(.el-statistic__head) {
  color: #714b67;
  font-weight: 600;
}

:deep(.el-statistic__number) {
  color: rgb(1, 128, 165);
  font-weight: 700;
}
</style>
